<?php
/**
 * @package	AcyMailing for Joomla!
 * @version	4.6.2
 * @author	acyba.com
 * @copyright	(C) 2009-2014 ACYBA S.A.R.L. All rights reserved.
 * @license	GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
 */
defined('_JEXEC') or die('Restricted access');
?><?php

class DataController extends acymailingController{

	function listing()
	{
		return $this->import();

	}

	function import(){
		if(!$this->isAllowed('subscriber','import')) return;
		JRequest::setVar( 'layout', 'import'  );
		return parent::display();
	}

	function export(){
		if(!$this->isAllowed('subscriber','export')) return;
		JRequest::setVar( 'layout', 'export'  );
		return parent::display();
	}

	function doimport(){
		if(!$this->isAllowed('subscriber','import')) return;
		JRequest::checkToken() or die( 'Invalid Token' );

		$function = JRequest::getCmd('importfrom');

		$importHelper = acymailing_get('helper.import');
		if(!$importHelper->$function()){
			return $this->import();
		}
		$app = JFactory::getApplication();
		$this->setRedirect(acymailing_completeLink($app->isAdmin() ? 'subscriber' : 'frontsubscriber',false,true));
	}


	function ajaxload(){
		if(!$this->isAllowed('subscriber','import')) return;

		$function = JRequest::getCmd('importfrom').'_ajax';

		$importHelper = acymailing_get('helper.import');
		$importHelper->$function();
		exit;
	}

	function doexport(){
		if(!$this->isAllowed('subscriber','export')) return;
		JRequest::checkToken() or die( 'Invalid Token' );

		acymailing_increasePerf();

		$filtersExport = JRequest::getVar('exportfilter');
		$listsToExport = JRequest::getVar('exportlists');
		$fieldsToExport = JRequest::getVar('exportdata');
		$fieldsToExportList = JRequest::getVar('exportdatalist');
		$fieldsToExportOthers = JRequest::getVar('exportdataother');
		$inseparator = JRequest::getString('exportseparator');
		$inseparator = str_replace(array('semicolon','colon','comma'),array(';',',',','),$inseparator);
		$exportFormat = JRequest::getString('exportformat');
		if(!in_array($inseparator,array(',',';'))) $inseparator = ';';

		$exportLists = array();

		if(!empty($filtersExport['subscribed'])){
			foreach($listsToExport as $listid => $checked){
				if(!empty($checked)) $exportLists[] = (int) $listid;
			}
		}

		$exportFields = array();
		$exportFieldsList = array();
		$exportFieldsOthers = array();
		$selectOthers = '';
		foreach($fieldsToExport as $fieldName => $checked){
			if(!empty($checked)) $exportFields[] = acymailing_secureField($fieldName);
		}
		foreach($fieldsToExportList as $fieldName => $checked){
			if(!empty($checked)) $exportFieldsList[] = acymailing_secureField($fieldName);
		}
		if(!empty($fieldsToExportOthers)){
			foreach($fieldsToExportOthers as $fieldName => $checked){
				if(!empty($checked)) $exportFieldsOthers[] = acymailing_secureField($fieldName);
			}
		}

		$selectFields = 's.`'.implode('`, s.`',$exportFields).'`';

		$config = acymailing_config();
		$newConfig = new stdClass();
		$newConfig->export_fields = implode(',',array_merge($exportFields,$exportFieldsOthers,$exportFieldsList));
		$newConfig->export_lists = implode(',',$exportLists);
		$newConfig->export_separator = JRequest::getString('exportseparator');
		$newConfig->export_format = $exportFormat;
		$filterActive = array();
		foreach($filtersExport as $filterKey => $value){
			if($value == 1) $filterActive[] = $filterKey;
		}
		$newConfig->export_filters = implode(',',$filterActive);
		$config->save($newConfig);

		$where = array();
		if(empty($exportLists)){
			$querySelect = 'SELECT s.`subid`, '.$selectFields.' FROM '.acymailing_table('subscriber').' as s';
		}else{
			$querySelect = 'SELECT DISTINCT s.`subid`, '.$selectFields.' FROM '.acymailing_table('listsub').' as a JOIN '.acymailing_table('subscriber').' as s on a.subid = s.subid';
			$where[] = 'a.listid IN ('.implode(',',$exportLists).')';
			$where[] = 'a.status = 1';
		}

		if(!empty($filtersExport['confirmed'])) $where[] = 's.confirmed = 1';
		if(!empty($filtersExport['registered'])) $where[] = 's.userid > 0';
		if(!empty($filtersExport['enabled'])) $where[] = 's.enabled = 1';

		if(JRequest::getInt('sessionvalues') AND !empty($_SESSION['acymailing']['exportusers'])){
			$where[] = 's.subid IN ('.implode(',',$_SESSION['acymailing']['exportusers']).')';
		}

		$query = $querySelect;
		if(!empty($where)) $query .= ' WHERE ('.implode(') AND (',$where).')';
		if(JRequest::getInt('sessionquery')){
			$currentSession = JFactory::getSession();
			$selectOthers = '';
			if(!empty($exportFieldsOthers)){
				foreach($exportFieldsOthers as $oneField){
					$selectOthers .= ' , '.$oneField.' AS '.str_replace('.','_',$oneField);
				}
			}
			$query = 'SELECT DISTINCT s.`subid`, '.$selectFields.$selectOthers.' '.$currentSession->get('acyexportquery');
		}
		$query .= ' ORDER BY s.subid';

		$db = JFactory::getDBO();
		$encodingClass = acymailing_get('helper.encoding');
		$exportHelper = acymailing_get('helper.export');

		$fileName = 'export_'.date('Y-m-d');
		if(!empty($exportLists)){
			$fileName = '';
			$db->setQuery('SELECT name FROM #__acymailing_list WHERE listid IN ('.implode(',',$exportLists).')');
			$allExportedLists = $db->loadObjectList();
			foreach($allExportedLists as $oneList){
				$fileName .= '__'.$oneList->name;
			}
			$fileName = trim($fileName,'__');
		}

		$exportHelper->addHeaders($fileName);

		$eol= "\r\n";
		$before = '"';
		$separator = '"'.$inseparator.'"';
		$after = '"';

		$allFields = array_merge($exportFields,$exportFieldsOthers);
		if(!empty($exportFieldsList)){
			$allFields = array_merge($allFields,$exportFieldsList);
			$selectFields = 'l.`'.implode('`, l.`',$exportFieldsList).'`';
			$selectFields = str_replace('listname', 'name', $selectFields);
		}

		echo $before.implode($separator,$allFields).$after.$eol;

		if(acymailing_bytes(ini_get('memory_limit'))>150000000){
			$nbExport = 50000;
		}elseif(acymailing_bytes(ini_get('memory_limit'))>80000000){
			$nbExport = 15000;
		}else{
			$nbExport = 5000;
		}

		if(!empty($exportFieldsList)) $nbExport = 500;

		$valDep = 0;
		$dateFields =array('created', 'confirmed_date', 'lastopen_date', 'lastclick_date','lastsent_date', 'userstats_opendate', 'userstats_senddate', 'urlclick_date', 'hist_date');
		do{
			$db->setQuery($query . ' LIMIT ' . $valDep . ', '.$nbExport);
			$valDep += $nbExport;
			$allData = $db->loadAssocList();
			if(empty($allData)) break;
			$dataUser = array();
			$subids = array();
			for($i=0,$a=count($allData);$i<$a;$i++){
				$subids[] = (int) $allData[$i]['subid'];
				if(!in_array('subid',$exportFields)) array_shift($allData[$i]);

				foreach($allData[$i] as $fieldName=>$oneUser){
					if(!in_array($fieldName, $dateFields)){
						$dataUser[$subids[$i]][$fieldName] = $oneUser;
					}else{
						$dataUser[$subids[$i]][$fieldName] = acymailing_getDate($oneUser,'%Y-%m-%d %H:%M:%S');
					}
				}
			}
			if(!empty($exportFieldsList) && !empty($subids)){
				$queryList = 'SELECT '. $selectFields .', ls.subid FROM #__acymailing_listsub as ls JOIN #__acymailing_list as l ON ls.listid=l.listid JOIN #__acymailing_subscriber as s on ls.subid = s.subid WHERE (ls.status = 1) and ls.subid IN ('.implode(',',$subids).')';
				if(!empty($exportLists)) $queryList .= ' AND ls.listid IN ('.implode(',',$exportLists).')';
				$db->setQuery($queryList);
				$resList = $db->loadObjectList();
				$userListid = array();
				$userListname = array();
				foreach($resList as $listsub){
					if(in_array('listid', $exportFieldsList)) $userListid[$listsub->subid] = empty($userListid[$listsub->subid])?$listsub->listid:$userListid[$listsub->subid].' - '.$listsub->listid;
					if(in_array('listname', $exportFieldsList)) $userListname[$listsub->subid] = empty($userListname[$listsub->subid])?$listsub->name:$userListname[$listsub->subid].' - '.$listsub->name;
				}
			}
			foreach($subids as $subid){
				if(!empty($exportFieldsList)){
					$listDetail = array();
					if(in_array('listid', $exportFieldsList)) $listDetail[] = !empty($userListid[$subid])?$userListid[$subid]:'';
					if(in_array('listname', $exportFieldsList)) $listDetail[] = !empty($userListname[$subid])?$userListname[$subid]:'';
					$dataexport = implode($separator,$dataUser[$subid]).$separator.implode($separator, $listDetail);
				}else{
					$dataexport = implode($separator,$dataUser[$subid]);
				}
				echo $before.$encodingClass->change($dataexport,'UTF-8',$exportFormat).$after.$eol;
			}
		} while(!empty($allData));
		exit;
	}
}
